package com.cloudfun.campusshare.service.impl;

import com.cloudfun.campusshare.common.model.vo.BsAresListVO;
import com.cloudfun.campusshare.common.response.PageResult;
import com.cloudfun.campusshare.entity.BsAreaEntity;
import com.cloudfun.campusshare.repo.BsAreaEntityRepo;
import com.cloudfun.campusshare.service.BsAreaService;
import com.cloudfun.campusshare.util.BeanCopyUtil;
import com.cloudfun.campusshare.util.hsq.StringUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : zhangyongjie
 * @version : 1.0
 * @createTime : 2021/3/29 18:33
 * @description :
 */
@Service
public class BsAreaServiceImpl implements BsAreaService {

    @Resource
    private BsAreaEntityRepo bsAreaEntityRepo;

    @Override
    public PageResult<BsAresListVO> queryAreaList(Pageable pageable, String keyword, Integer level, String parentCode) {
        Page<BsAreaEntity> all = bsAreaEntityRepo.findAll(assembleCon(keyword, level, parentCode), pageable);
        return new PageResult<>(all.getTotalElements(),all.stream().map(x -> BeanCopyUtil.copy(x,BsAresListVO.class)).collect(Collectors.toList()));
    }


    private Specification<BsAreaEntity> assembleCon(String keyword, Integer level, String parentCode){
        return (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = Lists.newArrayList();
            predicates.add(criteriaBuilder.equal(root.get("level"),level));
            if(StringUtils.isNotBlank(parentCode)){
                predicates.add(criteriaBuilder.equal(root.get("parentCode"),parentCode));
            }
            if(org.apache.commons.lang3.StringUtils.isNotBlank(keyword)){
                predicates.add(criteriaBuilder.like(root.get("areaName"),"'"+keyword+"'"));
            }
            Predicate[] preArr = new Predicate[predicates.size()];
            return criteriaBuilder.and(predicates.toArray(preArr));
        };
    }
}
